Load Libraries

library(tidyverse)
library(sf)
library(plotly)
library(hrbrthemes)

Load Data

# Import maps
landkreise_in_germany <- read_sf("data/landkreise/landkreise-in-germany.shp")
plz_gebiete <- read_sf("data/plz-gebiete/plz-2stellig.shp")

# Import tankstation data
stations_2019 <- read_csv("data/stations/stations.csv") %>% 
  mutate(post_2stellig = substring(post_code, 1, 2))
stations_2019 %>%
  select(uuid, brand, city, longitude, latitude) %>% 
  head()

Get the top 10 brand names

top_10_brands <- stations_2019 %>% 
  count(brand) %>%
  arrange(desc(n)) %>% 
  filter(!is.na(brand)) %>% 
  head(10) %>% 
  pull(brand)

top_10_brands
##  [1] "ARAL"       "Shell"      "ESSO"       "TOTAL"      "AVIA"      
##  [6] "JET"        "STAR"       "Agip"       "Raiffeisen" "HEM"

Plot Top Brands in Germany

# Filter stations and transform longitude and latitude
geo <- stations_2019 %>% 
  filter(brand %in% top_10_brands[1:5]) %>%
  filter(latitude > 0 & longitude > 0) %>% 
  sample_frac(0.1) %>% 
  sf::st_as_sf(coords = c("longitude", "latitude"), crs=4326) %>% 
  sf::st_transform(crs=4326)

# Combine data with coordinates
station_coords <- cbind(geo, sf::st_coordinates(geo))

# Plot german map and points from station_cords on top
plt <- ggplot() + 
  geom_sf(data=landkreise_in_germany, alpha=0.2, colour="grey") +
  geom_point(data=station_coords, aes(X, Y, fill=brand), alpha=0.8) +
  hrbrthemes::theme_ipsum_tw()

plotly::ggplotly(plt)

Plot by Zip and Gas Stations

brand_zip <- stations_2019 %>% 
  filter(brand %in% top_10_brands[1:5]) %>%
  group_by(post_2stellig, brand) %>% 
  summarise(count = n()) %>% 
  ungroup()

zip_plt <- brand_zip %>% 
  left_join(plz_gebiete, by=c("post_2stellig" = "plz")) %>% 
  ggplot() +
  geom_sf(aes(fill=count)) +
  coord_sf(crs = st_crs(4326)) +
  facet_wrap(~ brand) +
  scale_fill_gradient2(low="white", mid="yellow", high="red", midpoint = 27) +
  hrbrthemes::theme_ipsum_tw()

zip_plt